<?php
/**
 * Created by xun at 2020/5/14
 */

namespace app\storage;


class WechatHelper
{
    use Singleton;

    public function getAccessToken() {

        $pool = MysqlPool::getInstance();
        $mysqli = $pool->getConnection();
        $appid = Config::getConfig('extend.wechat.appid');
        $secret = Config::getConfig('extend.wechat.secret');
        $sql = "SELECT * FROM `zzb_acc` ac WHERE ac.`app_id` = '{$appid}' ORDER BY ac.`createtime` DESC LIMIT 1";
        $r = $mysqli->query($sql);
        if (!$r) {
            echo "get history error.\n";
            echo $mysqli->error . "\n";
        }
        $result = null;
        while ($row = $r->fetch_assoc()) {
            $result = $row;
        }
        if (time() - $result['createtime'] < 7200) {
            return $result['acc'];
        }
        // access token 过期
        $ch  = curl_init();
        curl_setopt($ch, CURLOPT_URL, "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appid}&secret={$secret}");
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($ch);
        curl_close($ch);
        $data = json_decode($output, true);
        $time = time();
        $sql = "INSERT INTO `zzb_acc` (
                    `acc`,
                    `createtime`,
                    `app_id`
                ) VALUES (
                    '{$data['access_token']}',
                    '{$time}',
                    '{$appid}'
                )";
        $r = $mysqli->query($sql);
        if (!$r) {
            echo "insert row error.\n";
            echo $mysqli->error . "\n";
        }
        $pool->free($mysqli);
        return $data['access_token'];
    }

}